package com.bcinfo.iccard.msg;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import com.bcinfo.iccard.busi.BusinessHandlerFactory;
import com.bcinfo.iccard.enums.Constants;
import com.bcinfo.iccard.util.DateTimeUtils;
import com.solab.iso8583.IsoMessage;
import com.solab.iso8583.IsoType;
import com.solab.iso8583.MessageFactory;
/**
 * 自定义业务消息处理器
 * @author wangguangchun
 *
 */
public class ISOMessageHandler extends IoHandlerAdapter {
	private static Logger _logger=Logger.getLogger(ISOMessageHandler.class);
	//iso8583消息工厂,提供iso8583报文解析和打包
    private MessageFactory<IsoMessage> mfact=ISOMessageFactory.getInstance();
    //业务处理器工厂
    private BusinessHandlerFactory businessHandlerFactory;
	//当一个客户端连接进入时  
    @Override  
    public void sessionOpened(IoSession session)throws Exception {  
    	_logger.info("incoming client:"+session.getRemoteAddress());  
    }  
    //当客户端发送消息到达时  
    @Override  
    public void messageReceived(IoSession session, Object message)throws Exception {  
        String s = message.toString();  
        _logger.info("client send message is:"+s);
        Message msg=(Message)message;
        if(msg.getMsg()!=null){
        	IsoMessage req=msg.getMsg();
        	int type=req.getType();
        	if(Constants.MSG_TYPES.containsKey(type)){
        		//根据消息类型调用业务处理器进行业务处理
        	    IsoMessage resp=mfact.createResponse(msg.getMsg());
        	    resp.clearAll();
        		resp.setValue(12, DateTimeUtils.getHourMinuteSec(), IsoType.NUMERIC, 6);
        		resp.setValue(13, DateTimeUtils.getYearMonthDay(), IsoType.NUMERIC, 8);
        		businessHandlerFactory.getHandler(type).invokeHandleBusiness(req, resp);
        		msg.setMsg(resp);
            	msg.exchange();
            	session.write(msg);
            	session.close(false);
        	}else{
        		//无操作类型，构造失败响应
            	IsoMessage response=mfact.createResponse(msg.getMsg());
            	response.setValue(39, "30", IsoType.ALPHA, 2);
            	response.setValue(12, DateTimeUtils.getHourMinuteSec(), IsoType.NUMERIC, 6);
            	response.setValue(13, DateTimeUtils.getYearMonthDay(), IsoType.NUMERIC, 8);
            	msg.setMsg(response);
            	msg.exchange();
            	session.write(msg);
        	}
        }
        //session.write(msg);
		// Create a response
        session.close(false);
    }  
    //当一个客户端连接关闭时  
    @Override  
    public void sessionClosed(IoSession session)throws Exception {  
    	_logger.info("client from "+session.getRemoteAddress()+" closed!");  
    }
    //处理例外
    @Override
    public void exceptionCaught(IoSession session, Throwable cause)
    		throws Exception {
    	// TODO Auto-generated method stub
    	_logger.error("exception caught:"+ExceptionUtils.getStackTrace(cause));
    	session.close(false);
    }
	public BusinessHandlerFactory getBusinessHandlerFactory() {
		return businessHandlerFactory;
	}
	public void setBusinessHandlerFactory(
			BusinessHandlerFactory businessHandlerFactory) {
		this.businessHandlerFactory = businessHandlerFactory;
	}
    
}  
